// 文件：OxygenChartFragment.kt
package kt_test.ui.fragment

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.Toast
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.healthapp.R
import com.github.mikephil.charting.charts.LineChart
import com.github.mikephil.charting.data.Entry
import com.github.mikephil.charting.data.LineData
import com.github.mikephil.charting.data.LineDataSet
import kt_test.room.entity.OxygenSampleEntity
import kt_test.viewmodel.OxygenSampleViewModel

class OxygenChartFragment : Fragment() {

    private lateinit var lineChart: LineChart
    private lateinit var recyclerView: RecyclerView
    private lateinit var adapter: OxygenDataViewerFragment.OxygenSampleAdapter

    private val viewModel: OxygenSampleViewModel by viewModels()

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        val view = inflater.inflate(R.layout.fragment_oxygen_chart, container, false)

        lineChart = view.findViewById(R.id.line_chart)
        recyclerView = view.findViewById(R.id.rv_samples)

        adapter = OxygenDataViewerFragment.OxygenSampleAdapter()
        recyclerView.layoutManager = LinearLayoutManager(requireContext())
        recyclerView.adapter = adapter

        val userId = arguments?.getString("userId")
        val startTime = arguments?.getString("startTime")
        val endTime = arguments?.getString("endTime")
        val btnBack = view.findViewById<Button>(R.id.btn_back)
        btnBack.setOnClickListener {
            parentFragmentManager.popBackStack()
        }
        viewModel.querySamples(userId, startTime, endTime)

        viewModel.samples.observe(viewLifecycleOwner, Observer { list ->
            adapter.updateData(list)
            if (list.isNotEmpty()) {
                drawLineChart(list)
                lineChart.visibility = View.VISIBLE
            } else {
                Toast.makeText(requireContext(), "没有可绘制的数据", Toast.LENGTH_SHORT).show()
            }
        })

        return view
    }

    private fun drawLineChart(samples: List<OxygenSampleEntity>) {
        val entries = samples.mapIndexed { index, sample ->
            Entry(index.toFloat(), sample.spo2.toFloat())
        }

        val dataSet = LineDataSet(entries, "血氧变化趋势")
        dataSet.lineWidth = 2f
        dataSet.circleRadius = 3f
        dataSet.setDrawValues(false)
        dataSet.setDrawCircles(true)

        val lineData = LineData(dataSet)
        lineChart.data = lineData
        lineChart.description.text = "X轴：采样顺序，Y轴：血氧值(%)"
        lineChart.invalidate()
    }

    companion object {
        fun newInstance(userId: String?, startTime: String?, endTime: String?): OxygenChartFragment {
            val fragment = OxygenChartFragment()
            val args = Bundle().apply {
                putString("userId", userId)
                putString("startTime", startTime)
                putString("endTime", endTime)
            }
            fragment.arguments = args
            return fragment
        }
    }
}